package com.yanxu;

import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;

/**
 * @author 折戟沉沙铁未销
 * @version V1.0
 * @date 2024/5/22-2024
 * @Description: 异步发送消息
 */
public class AsyncMessage {
    public static void main(String[] args) throws Exception {
        //定义 producer
        DefaultMQProducer producer = new DefaultMQProducer("async-message-study");

        //定义 NameServer地址
        producer.setNamesrvAddr("139.129.91.21:9876");
        //消息的超时时间
        producer.setSendMsgTimeout(5000);

        producer.start();

        //循环发送消息
        for (int i = 0; i < 10; i++) {
            Message message = new Message(
                    "async-message",
                    "tag-async",
                    "key-async", ("message_" + i).getBytes()
            );
            producer.send(message, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    // SEND_OK,
                    // FLUSH_DISK_TIMEOUT,    主节点刷盘超时
                    // FLUSH_SLAVE_TIMEOUT,   从节点刷盘超时
                    // SLAVE_NOT_AVAILABLE,   从节点不可用
                    SendStatus sendStatus = sendResult.getSendStatus();
                }

                @Override
                public void onException(Throwable e) {
                    System.out.println("消息发送失败!!!");
                }
            });
        }
    }
}